﻿using CoreShop.App.Test;
using CoreShop.App.Units.Helper;
using CoreShop.App.Units.Interface;
using CoreShop.Library;
using CoreShop.Model;
using CoreShop.Model.FromBody;
using CoreShop.Model.UI;
using CoreShop.PrintService;
using CoreShop.Services;
using IWshRuntimeLibrary;
using Loading;
using Microsoft.Win32;
using Newtonsoft.Json;
using NPOI.SS.UserModel;
using SqlSugar;
using SqlSugar.Extensions;
using Sunny.UI;
using Sunny.UI.Win32;
using System;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Runtime.Remoting.Contexts;
using System.Security.Policy;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using Yitter.IdGenerator;
using static CoreShop.Model.FromBody.DataResultModel;
using static System.Windows.Forms.AxHost;

namespace CoreShop.App
{
    public partial class frmLogin : UIForm
    {
        OpaqueCommand cmd = new OpaqueCommand();
        public frmLogin()
        {
            InitializeComponent();
            keyborad.Top = this.Height - keyborad.Height;
            keyborad.Visible = false;
            txtUserCode.TextBox.GotFocus += txtSendKey_GotFocus;
            txtPassword.TextBox.GotFocus += txtPassword_GotFocus;
        }

        private void txtSendKey_GotFocus(object sender, System.EventArgs e)
        {
            this.txtUserCode.Focus();
            keyborad.SetTextBox((UIEdit)sender);
        }

        private void txtPassword_GotFocus(object sender, System.EventArgs e)
        {
            this.txtPassword.Focus();
            keyborad.SetTextBox((UIEdit)sender);
        }

        private void btnClose_Click(object sender, System.EventArgs e)
        {
            //string mContent = "posNC系统中已经存在来源为&apos;1031202422160436&apos;销售订单，编号为：SO302024022100003458";
            //string[] strlist = mContent.Split('：');
            //if (strlist.Count() > 0)
            //{
            //    string sBillNo = strlist[1];
            //}
            this.Close();
        }

        private void frmLogin_Load(object sender, System.EventArgs e)
        {
            string filename = System.Windows.Forms.Application.StartupPath + "\\Image\\login.png";
            if (System.IO.File.Exists(filename))
            {
                pnlImg.BackgroundImage = System.Drawing.Image.FromFile(filename);
            }
            lingVersion.Text = AppConstVars.sPosVersion;
            txtUserCode.Text = IniFiles.ReadIniData("Local", "UserID").ObjToString();
            if (string.IsNullOrEmpty(txtUserCode.Text)) ProcessUtil.SetWebUrlInit();
            int sRememberPsd = CommFunc.ConvertToInt32(Security.Decrypt(IniFiles.ReadIniData("Local", "RememberPsd").ObjToString()));
            if (sRememberPsd == 1)
            {
                chbSavePsd.Checked = true;
                string mPassword = IniFiles.ReadIniData("Local", "UserPassword");
                if (!mPassword.IsNullOrEmpty()) txtPassword.Text = Security.Decrypt(mPassword);
            }

            //全部显示
            string sShowFullScreen = CommFunc.ConvertToString(IniFiles.ReadIniData("Local", "ShowFullScreen"));
            if (sShowFullScreen == "0") AppConstVars.showFullScreen = false;
            SetDBConnect();
        }

        private void SaveUserLogin()
        {
            if (txtUserCode.Text.Trim() == "200161")
            {
                IniFiles.IniWriteValue("Local", "UserID", "");
                IniFiles.IniWriteValue("Local", "RememberPsd", "");
                IniFiles.IniWriteValue("Local", "UserPassword", "");
            }
            else
            {
                IniFiles.IniWriteValue("Local", "UserID", txtUserCode.Text);
                int mRememberPsd = 0;
                if (chbSavePsd.Checked) mRememberPsd = 1;
                IniFiles.IniWriteValue("Local", "RememberPsd", Security.Encrypt(mRememberPsd.ToString()));
                IniFiles.IniWriteValue("Local", "UserPassword", Security.Encrypt(txtPassword.Text));
            }
        }


        /// <summary>
        /// 检查非本店的数据，如果有，要清理
        /// </summary>
        /// <returns></returns>
        private bool CheckStoreData(sysuser loginUser)
        {
            var userServices = new sysuserServices();
            var otherUser = userServices.IsAny(p => p.storeId != loginUser.storeId);
            if (!otherUser) otherUser = new corecmsstoreServices().IsAny(p => p.id != loginUser.storeId);
            //if (!otherUser) otherUser = new corecmsfoodServices().IsAny(p => p.storeId != loginUser.storeId);
            if (otherUser)
            {
                var demoUser = userServices.IsAny(p => p.storeId != loginUser.storeId && p.corpId < 200200);               

                if ((!demoUser) && (!ShowAskDialog("提示：", "登录商户发生改变，将初始化所有数据，要继续吗?", UIStyle.Red))) return false;
                                
                userServices.ClearBaseData(loginUser.storeId, loginUser);
                String path = AppConstVars.SecondScreemImg;
                if (Directory.Exists(path)) FoodImgService.DeleteFolder(AppConstVars.SecondScreemImg);
                ProcessUtil.SetSystemInit();//系统初始化
            }
            return true;
        }

        private bool ChkDBConnect()
        {
            bool isDbConnect = false;
            try
            {
                var corecmssystemsetup = new corecmssystemsetupService().GetFirst(p => p.id > 0);
                isDbConnect = true;
            }
            catch (Exception ex)
            {
                MySQLServiceStarter.StartMySQLService();
            }
            return isDbConnect;
        }

        private bool SetDBConnect()
        {
            bool isDbConnect = false;
            try
            {
                ChkDBConnect();
                new DataHelper().SetDataUpgrade();//自动升级数据库
                var corecmssystemsetup = new corecmssystemsetupService().GetFirst(p => p.id > 0);
                if (corecmssystemsetup != null)
                {
                    AppConstVars.sUrl = corecmssystemsetup.adminApiUrl;
                    if (string.IsNullOrEmpty(AppConstVars.sUrl))
                    {
                        ProcessUtil.SetWebUrlInit();
                        isDbConnect = true;
                    }
                }
                isDbConnect = true;
            }
            catch (Exception ex)
            {
                UIMessageBox.Show(ex.Message);
                UIMessageBox.Show("连接本地数据库失败，请重新连接。");
            }
            if (!isDbConnect)
            {
                var frm = new frmDBConnect();
                frm.Owner = this;
                if (frm.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    isDbConnect = true;
                }
                frm.Dispose();
            }
            return isDbConnect;
        }

        /// <summary>
        /// 自动退出演示用户
        /// </summary>
        private async Task<corecmsstore> LogoutByPos(corecmsstore storeModel)
        {
            if ((storeModel != null) && (storeModel.corpId < 200200))
            {
                storeModel.deviceId = "";
                new corecmsstoreServices().UpdateAsync(storeModel);
                return await GetStoreModelAsync(storeModel);
            }
            return storeModel;
        }

        private async Task<corecmsstore> GetStoreModelAsync(corecmsstore storeModel)
        {
            string deviceId = CommFunc.GetMacByWmi("");
            if (storeModel == null || !storeModel.deviceId.Equals(deviceId))
                storeModel = await PosRegister(storeModel, txtUserCode.Text.Trim(), txtPassword.Text.Trim(), deviceId);
            if (storeModel == null)
            {
                UIMessageBox.Show("无法访问远程服务器，请联系软件服务商。");
                return null;
            }
            return storeModel;
        }

        private async void btnLogin_Click(object sender, System.EventArgs e)
        {
            string dayOfWeek = (((int)DateTime.Now.DayOfWeek - 1 + 7) % 7 + 1).ToString();

            string sDateTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
            string sName = GlobalEnumVars.SxfTranSts.FAIL.ToString();
            if (txtUserCode.Text.Trim().Length < 6 && false)
            {
                UIMessageBox.Show("请输入正确的用户编码。", "提示：", UIStyle.Green, UIMessageBoxButtons.OK);
                return;
            }

            if (!SetDBConnect()) return;

            try
            {
                string passwordEn = Security.Encrypt(txtPassword.Text.Trim());
                var userSvr = new sysuserServices();
                AppConstVars.sysUser = userSvr.QueryByNameAsync(txtUserCode.Text.Trim(), passwordEn, AppConstVars.adminPassword);
                var storeModel = new corecmsstoreServices().GetFirst(p => p.id > 0);
                if (AppConstVars.sysUser == null)
                {
                    //检查是否已注册
                    storeModel = await GetStoreModelAsync(storeModel);
                    if (storeModel == null) return;
                    AppConstVars.sysUser = new sysuser();
                    //执行远程登录
                    var result = await LoginByPos(txtUserCode.Text.Trim(), txtPassword.Text.Trim(), storeModel, AppConstVars.sysUser);
                    AppConstVars.sysUser = result.data;
                    if (result.code == 2) return;
                    if ((AppConstVars.sysUser == null) && (result.code == 50009))
                    {
                        lblLogoutStore.Visible = true;
                        UIMessageBox.Show("如要在本机登录新的帐号，必须先注销原绑定帐号。", "提示：", UIStyle.Green, UIMessageBoxButtons.OK);
                        return;
                    }
                }
                if (AppConstVars.sysUser == null) return;

                AppConstVars.sysStore = storeModel;
                AppConstVars.sysUser.pswStr = txtPassword.Text.Trim();
                if (AppConstVars.sysUser == null) return;
                GetPosRemoteData();//每次登录下载数据
                SaveUserLogin();//保存本次登录信息
                CreateShortcut(false);//建后台桌面快捷方式
                ClearHistoryData();//清一些多余的历史数据
                InitFilePara();//初始化文件参数
                ProcessUtil.GetIniParaSetup();//获取本地ini参数
                new ActivitieUtil().ActivitieInit();//初始化促销
                //ProcessUtil.SetSystemInit();//系统初始化
                if (passwordEn == AppConstVars.adminPassword) AppConstVars.isAdminUser = true;
                
                DialogResult = DialogResult.OK;
            }
            catch (Exception ex)
            {
                UIMessageBox.Show("错误01："+ex.Message);
            }            
        }

        /// <summary>
        /// 初始化文件参数
        /// </summary>
        private void InitFilePara()
        {
            string imagePath = System.Windows.Forms.Application.StartupPath + "\\foodimg\\";
            if (!Directory.Exists(imagePath)) Directory.CreateDirectory(imagePath);
        }

        private async Task<corecmsstore> PosRegister(corecmsstore store, string userCode, string password, string deviceId)
        {           
            var result = await SystemApiUtil.PosRegister(userCode, password, deviceId);
            //var rs = new PosRemoteServices("").PosRegister(userCode, password, deviceId, ref register);
            if (result.code != 0)
            {
                UIMessageBox.Show(result.msg, "错误：", UIStyle.Green, UIMessageBoxButtons.OK);
                return null;
            }
            FMRegister register = result.data;
            if (register == null) return null;
            //注册成功更新store表
            var storeService = new corecmsstoreServices();
            //var store = storeService.GetFirst(p => p.id > 0);

            if (store == null) store = new corecmsstore();
            //租户Id
            store.corpId = register.tenantId;
            store.deviceId = register.deviceId;
            //仓库名称
            store.storeName = register.warehouseName;
            store.createTime = register.registerDate;
            store.registerNo = register.registerNo;
            //部门id
            store.branchId = register.branchId;
            store.branchName = register.branchName;
            store.parentTenantId = CommFunc.ConvertToInt32(register.parentTenantId);//上级商户Id
            storeService.Delete(store);
            store.id = register.warehouseId;//仓库ID
            storeService.InsertOrUpdate(store);
            return store;
        }

        private async Task<UserLoginResult> LoginByPos(string userCode, string password, corecmsstore store, sysuser user)
        {
            UserLoginResult result = new UserLoginResult();
            var rs = await SystemApiUtil.LoginByPos(userCode, password, store);
            if (rs.code == 50009)
            {
                store = await LogoutByPos(store);//注销
                rs = await SystemApiUtil.LoginByPos(userCode, password, store);
            }
            if (rs.code != 0)
            {
                UIMessageBox.Show(rs.msg, "错误：", UIStyle.Green, UIMessageBoxButtons.OK);
                result.code = rs.code;
                return result;
            }

            LoginBody loginBody = JsonConvert.DeserializeObject<LoginBody>(rs.data.ToString());
            loginBody.userInfo.password = password;
            new sysuserServices().SetLoginData(ref user, loginBody, store);
            SystemApiUtil.GetUserRoleInfo(AppConstVars.sysUser);
            SystemApiUtil.GetUserRouters(AppConstVars.sysUser);
            if (!CheckStoreData(user)) result.code = 2;
            result.data = user;
            return result;
        }


        /// <summary>
        /// 异步登录，
        /// </summary>
        /// <param name="userCode"></param>
        /// <param name="password"></param>
        private void SetUserLoginTast(string userCode, string password)
        {
            Thread newThread = new Thread(() => SetUserLoginThread(userCode, password));
            newThread.Start();
        }

        private async void SetUserLoginThread(string userCode, string password)
        {
            var store = new corecmsstoreServices().GetFirst(p => p.id > 0);
            LoginData loginInfo = new LoginData();
            var rs =await LoginByPos(userCode, password, store, null);
            LoginBody loginBody = JsonConvert.DeserializeObject<LoginBody>(rs.data.ToString());
            sysuser user = null;
            new sysuserServices().SetLoginData(ref user, loginBody, store);
            if (user != null) AppConstVars.sysUser = user;
        }

        private void GetPosRemoteData()
        {
            try
            {
                var exchange = new corecmsexchangeServices().GetFirst(p => p.storeId > 0);
                if ((AppConstVars.sysStore == null) || (AppConstVars.sysStore.id == 0))
                {
                    AppConstVars.sysStore = new corecmsstoreServices().GetById(AppConstVars.sysUser.storeId);
                    AppConstVars.sysUser.corpId = AppConstVars.sysStore.corpId;
                    AppConstVars.sysUser.corehubUrl = AppConstVars.systemsetup.corehubUrl;
                }
                if (exchange == null)
                {
                    exchange = new corecmsexchange();
                    exchange.storeId = AppConstVars.sysStore.id;
                    new corecmsexchangeServices().Insert(exchange);
                }
                else
                if (exchange.storeId != AppConstVars.sysStore.id)
                {
                    //删除当前配置信息
                    new corecmsexchangeServices().DeleteById(exchange.storeId);
                    exchange = new corecmsexchange();
                    exchange.storeId = AppConstVars.sysStore.id;
                    new corecmsexchangeServices().Insert(exchange);
                }
            }
            catch (Exception ex) { 
                UIMessageBox.Show("错误02:"+ex.Message);            
            }
        }

        /// <summary>
        /// 清一些多余的历史数据
        /// </summary>
        private void ClearHistoryData()
        {
            Thread newThread = new Thread(() => ProcessUtil.ClearHistoryData(AppConstVars.sysStore));
            newThread.Start();
        }

        private void btnLoginByCode_Click(object sender, System.EventArgs e)
        {
            btnLoginByCode.Selected = false;
            btnLoginByMsg.Selected = false;
            UIButton btn = (UIButton)sender;
            btn.Selected = true;
        }

        private void lblRegrist_Click(object sender, EventArgs e)
        {
            string url = IniFiles.ReadIniData("Local", "SysUrl").ObjToString();
            if (string.IsNullOrEmpty(url)) url = "https://erp.yzipos.com/";
            url = url + "/#/register";
            System.Diagnostics.Process.Start(url);
        }

        private void lblDownUpdate_Click(object sender, EventArgs e)
        {
            var frm = new frmSystemUpdate();
            frm.ShowDialog();
        }

        private void lbl_CreateShortcut_Click(object sender, EventArgs e)
        {
            CreateShortcut(false);
        }

        private void CreateShortcut(bool isShowTip)
        {
            try
            {
                string ss = Security.Encrypt("柚子收银后台");
                string web_url = IniFiles.ReadIniData("Local", "SysUrl").ObjToString();
                string sShortcutName = Security.Decrypt(IniFiles.ReadIniData("Local", "SysName").ObjToString());
                string sIcoFile = System.Windows.Forms.Application.StartupPath + "\\Images\\WebICO.ico";
                CreateShortcutOnDesktop(sShortcutName, web_url, null, sIcoFile);
                if (isShowTip) ShowInfoTip(sShortcutName + "添加成功！");
            }
            catch { }
        }

        public static void SetYunPosExchangeKill()
        {
            Process[] allProcess = Process.GetProcesses();
            foreach (Process p in allProcess)
            {
                string sProcessName = p.ProcessName.ToLower() + ".exe";
                if (sProcessName == "yunposexchange.exe")
                {
                    for (int i = 0; i < p.Threads.Count; i++) p.Threads[i].Dispose();
                    p.Kill();
                }
            }
        }

        /// <summary>
        /// 发通知给YunPosExchange
        /// </summary>
        /// <param name="isGetPara"></param>
        public static void SetYunPosExchange()
        {
            try
            {
                int sHostFlag = CommFunc.ConvertToInt32(IniFiles.ReadIniData("Local", "HostFlag"));
                if (sHostFlag != 1)
                {
                    SetYunPosExchangeKill();
                    return;
                }
                bool sIsShow = false;
                Process[] pros = Process.GetProcesses(); //获取本机所有进程
                for (int i = 0; i < pros.Length; i++)
                {
                    if (pros[i].ProcessName == "YunPosExchange") //名称为ProcessCommunication的进程
                    {
                        sIsShow = true;
                    }
                }
                if (!sIsShow)
                {
                    //启动交换工具
                    string toolPath = Application.StartupPath + "\\YunPosExchange.exe";
                    if (System.IO.File.Exists(toolPath))
                        Process.Start(toolPath);
                    else
                        UIMessageBox.Show("未发现数据控制台工具。", "提示");
                }
            }
            catch { }
        }

        /// <summary>
        /// 创建桌面快捷方式
        /// </summary>
        /// <remarks></remarks>
        public static void CreateShortcutOnDesktop(string shortcutName, string targetPath,
            string description = null, string iconLocation = null)
        {
            string desktop = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);//获取桌面文件夹路径
            CreateShortcut(desktop, shortcutName, targetPath, description, iconLocation);
        }

        public static void CreateShortcut(string directory, string shortcutName, string targetPath,
             string description = null, string iconLocation = null)
        {
            if (!System.IO.Directory.Exists(directory))
            {
                System.IO.Directory.CreateDirectory(directory);
            }

            string shortcutPath = Path.Combine(directory, string.Format("{0}.lnk", shortcutName));

            if (Path.GetExtension(shortcutPath) == "lnk")
            {
                MessageBox.Show("服务器无法访问或无法取得返回数据!");
                return;
            }

            //判断已经存在就返回。
            string desktop = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
            string[] desktopFiles = Directory.GetFiles(desktop, "*.lnk");
            string mTargetPathStr = targetPath.Replace("/", "").Replace("\\", "");
            for (int i = 0; i < desktopFiles.Length; i++)
            {
                string mFile = desktopFiles[i];
                IWshRuntimeLibrary.WshShell shell0 = new IWshRuntimeLibrary.WshShell();
                IWshRuntimeLibrary.IWshShortcut shortcut0 = (IWshRuntimeLibrary.IWshShortcut)shell0.CreateShortcut(mFile);
                string TargetPath0 = shortcut0.WorkingDirectory.Replace("/", "").Replace("\\", "");

                if (TargetPath0 == mTargetPathStr)
                {
                    //MessageBox.Show(targetPath);
                    return;
                }
            }

            WshShell shell = new WshShell();
            IWshShortcut shortcut = (IWshShortcut)shell.CreateShortcut(shortcutPath);//创建快捷方式对象
            shortcut.TargetPath = targetPath;//指定目标路径
            shortcut.WorkingDirectory = Path.GetDirectoryName(targetPath);//设置起始位置
            shortcut.WindowStyle = 1;//设置运行方式，默认为常规窗口
            shortcut.Description = description;//设置备注
            shortcut.IconLocation = string.IsNullOrWhiteSpace(iconLocation) ? targetPath : iconLocation;//设置图标路径
            shortcut.Save();//保存快捷方式
        }

        private void lblLogoutStore_Click(object sender, EventArgs e)
        {
            var storeModel = new corecmsstoreServices().GetFirst(p => p.id > 0);
            if (storeModel != null)
            {
                string msg = "要注销商户【" + storeModel.storeName + "】的本地设备绑定信息吗？";
                if (!ShowAskDialog("提示：", msg, UIStyle.Red)) return;
                storeModel.deviceId = "";
                new corecmsstoreServices().UpdateAsync(storeModel);
                UIMessageBox.Show("注销成功，请登录。");
                lblLogoutStore.Visible = false;
            }
        }

        private void frmLogin_Shown(object sender, EventArgs e)
        {
            if (txtUserCode.Text.IsNullOrEmpty())
            {
                txtUserCode.Focus();
            }
            else
            {
                txtPassword.Focus();
                txtPassword.SelectAll();
            }
        }

        private void KeyboardEx_ValueChanged(object sender, object value)
        {

        }

        private void button1_Click(object sender, EventArgs e)
        {
            cmd.ShowOpaqueLayer(pnl_Form, 125, true);
            try
            {
                //MessageBox.Show("ex.Message");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            finally
            {
                cmd.HideOpaqueLayer();
            }

        }

        private void txtUserCode_ButtonClick(object sender, EventArgs e)
        {
            keyborad.Visible = true;
            this.txtUserCode.Focus();
        }

        private void keyborad_OKButtonClick(object sender, string value)
        {
            keyborad.Visible = false;
        }

        private void txtPassword_ButtonClick(object sender, EventArgs e)
        {
            keyborad.Visible = true;
            this.txtPassword.Focus();
        }
    }
}
